<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="connect()">连接WS</button>
<input type="text" id="message" placeholder="输入消息">
<button onclick="send()">发送</button>
<div id="output"></div>

<script>
    let socket = null;

    function connect() {
        // 连接后端WebSocket端点
        socket = new WebSocket('ws://localhost:8080/ws');

        socket.onopen = () => {
            log('连接已建立');
        };

        socket.onmessage = (event) => {
            log('收到: ' + event.data);
        };

        socket.onclose = () => {
            log('连接已关闭');
        };
    }

    function send() {
        const message = document.getElementById('message').value;
        socket.send(message);
        log('发送: ' + message);
    }

    function log(msg) {
        const output = document.getElementById('output');
        output.innerHTML += `<p>${msg}</p>`;
    }
</script>
</body>
</html>